<template>
  <view class="container">
    <!-- 选择头像按钮 -->
    <button open-type="chooseAvatar" @chooseavatar="onChooseAvatar" style="margin-top: -450px; border-radius: 10px; width: 90px; height: 90px; overflow: hidden;">
      <image :src="avatarUrl || '/static/ava.png'" mode="aspectFill" style="margin-left: -12px; width: 90px; height: 90px;" />
    </button>

    <view class="nickName">
      <input class="nickname" type="nickname" :value="nickname" @input="handleInputChange" placeholder="请输入昵称" />
    </view>

    <!-- 授权登录按钮 -->
    <button @click="authorizeLogin" style="margin-top: 40px; width: 70%; background-color: #13AF12; color: white;">
      授权登录
    </button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      code: '',  // 存储登录凭证
      userInfo: {
        nickName: '', // 用户昵称
        avatarUrl: '', // 用户头像
      },
      nickname: '',  // 用户昵称
      openid: '',  // 用于存储openid
      tel: '17539209220',  // 用户电话
      pass: '111111',  // 密码
      avatarUrl: '',  // 用户头像 URL
    };
  },
  mounted() {
    // 页面加载时检查是否已经存储了用户信息
    const storedUserInfo = uni.getStorageSync('userInfo');
    if (storedUserInfo) {
      this.userInfo = storedUserInfo;
      this.nickname = storedUserInfo.nickName;
      this.avatarUrl = storedUserInfo.avatarUrl;
      // 跳过登录，直接进入首页
      uni.navigateTo({
        url: '/pages/home/home',  // 跳转到 list 页面
      });
    }
  },
  methods: {
    // 选择头像
    onChooseAvatar(e) {
      const { avatarUrl } = e.detail;
      this.avatarUrl = avatarUrl;  // 更新头像 URL
      this.userInfo.avatarUrl = avatarUrl;  // 同步到 userInfo
    },

    // 处理昵称输入变化
    handleInputChange(e) {
      this.nickname = e.detail.value;  // 更新昵称
      this.userInfo.nickName = e.detail.value;  // 同步到 userInfo
    },

    // 授权登录
    authorizeLogin() {
      const { userInfo, nickname } = this;

      // 判断头像和昵称是否填写完整
      if (!userInfo.avatarUrl || !nickname) {
        uni.showToast({
          title: '请上传头像并填写昵称',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      // 获取登录凭证并请求 session_key
      uni.login({
        success: (res) => {
          if (res.code) {
            this.code = res.code;
            this.getSessionKey(res.code);  // 请求 session_key
          } else {
            console.error('登录失败！' + res.errMsg);
          }
        },
        fail: (err) => {
          console.error('登录失败', err);
        }
      });
    },

    // 请求接口获取 session_key
    getSessionKey(code) {
      const appid = 'wx3c0518fdc0f73347';
      const secret = 'ecec3ad8ba75497227d4dbf316c6c336';

      uni.request({
        url: 'https://yiliao.kuxia.top/app/user/getsessionkey', 
        method: 'POST',
        data: { code, appid, secret },
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 1) {
            this.openid = res.data.data.openid;
            this.sendUserInfo();  // 请求 session_key 成功后提交用户信息
          } else {
            console.error('请求失败:', res.data.message || res.data.msg);
          }
        },
        fail: (err) => {
          console.error('请求失败:', err.message);
        }
      });
    },

    // 提交用户信息
    sendUserInfo() {
      const { userInfo, openid, tel, pass } = this;

      if (!userInfo.avatarUrl || !openid || !userInfo.nickName) {
        console.error('头像、昵称或openid未填写');
        return;
      }

      // 准备请求参数，确保与接口要求匹配
      const userData = {
        openid: openid,  // 必须传递openid
        avatar: userInfo.avatarUrl,  // 传递头像URL
        nickname: userInfo.nickName,  // 传递昵称
        tel: tel,  // 电话
        pass: pass,  // 密码
      };

      uni.request({
        url: 'https://yiliao.kuxia.top/app/user/empower',  // 后端接口
        method: 'POST',
        data: userData,
        success: (res) => {
          if (res.data.code === 1) {
			  uni.request({
			  		url: "https://yiliao.kuxia.top/app/user/index",
			  		method: "POST",
			  		data: {
			  			tel: 17539209220,
			  			pass: 111111,
			  		},
			  		success: (res) => {
			  			if (res.data.code === 1) {
			  				// 登录成功，将用户信息存储到本地
			  				uni.setStorageSync("data", JSON.stringify(res.data)); // 存储用户信息
			  				uni.setStorageSync("ipp", password.value); // 存储密码
			  
			  				
			  
			  				uni.showToast({
			  					title: "登录成功",
			  					icon: "success",
			  					duration: 2000,
			  				});
			  
			  				setTimeout(() => {
			  					// 跳转到主页
			  					uni.redirectTo({
			  						url: "/pages/home/home",
			  					});
			  				}, 3000);
			  			} else {
			  				uni.showToast({
			  					title: "密码有误，请检查！",
			  					icon: "none",
			  					duration: 2000,
			  				});
			  			}
			  		},
			  		fail: () => {
			  			uni.showToast({
			  				title: "账号不存在或密码错误",
			  				icon: "none",
			  				duration: 2000,
			  			});
			  		},
			  	});
			  
            // 登录成功后，将用户信息存储到本地
            uni.setStorageSync('userInfo', userInfo);
            uni.navigateTo({
              url: '/pages/home/home',  // 跳转到首页
            });
          } else {
            console.error('请求失败:', res.data.message || res.data.msg);
            uni.showToast({
              title: '请求失败',
              icon: 'none',
            });
          }
        },
        fail: (err) => {
          console.error('请求失败:', err.message);
          uni.showToast({
            title: '请求失败',
            icon: 'none',
          });
        }
      });
    }
  }
};
</script>

<style scoped>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;  /* 禁止页面滚动 */
}

.nickName {
  width: 90%;
  font-weight: 600;
  margin-left: 82px;
  margin-top: -430px;
  position: fixed;
}

button {
  width: 70%;
  color: white;
  margin-top: 40px;
}

input {
  width: 80%;
  margin-left: 90px;
  position: fixed;
}
</style>
